package ferp.android.tasks.center;

import android.os.AsyncTask;
import ferp.android.managers.PollManager;
import ferp.center.client.Action;
import ferp.center.network.request.RequestPollSubmit;
import ferp.core.log.Log;
import ferp.poll.Poll;

/**
 * User: olegs
 * Date: 11/05/2014 14:34
 */
public class TaskPollSubmit extends AsyncTask<Void, Void, Boolean>
{
  public TaskPollSubmit(PollManager.Listener listener, String device, Poll poll, String answers)
  {
    this.poll = poll;
    this.device = device;
    this.answers = answers;
    this.listener = listener;
  }

  @Override
  protected void onPreExecute()
  {
    super.onPreExecute();

    if (answers != null)
      listener.onSubmitPollResultsStarted();
  }

  @Override
  protected Boolean doInBackground(Void... voids)
  {
    RequestPollSubmit request = new RequestPollSubmit();

    request.poll = poll.id();
    request.device = device;
    // handle the poll refused answer
    request.answers = answers == null ? Poll.REFUSED : answers;

    try
    {
      Boolean result = Action.execute(Action.POLL_SUBMIT, request, Boolean.class);

      return result != null && result;
    }
    catch (Exception e)
    {
      Log.error(Action.TAG, e);
    }

    return false;
  }

  @Override
  protected void onPostExecute(Boolean success)
  {
    super.onPostExecute(success);

    if (answers != null)
      listener.onSubmitPollResultsEnded(success, poll.bonus().value());
  }

  private final String device;
  private final Poll poll;
  private final String answers;
  private final PollManager.Listener listener;
}
